package com.kevin.framework.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Activity;

import com.kevin.framework.view.animation.ContentView;
import com.kevin.framework.view.animation.InjectView;

public class ViewInjectUtils {
	private static final String SET_CONTENTVIEW = "setContentView";
	private static final String FIND_VIEW_BY_ID = "findViewById";
	
	public static void inject(Activity activity) {
		injectContentView(activity);
		
		injectViews(activity);
	}
	
	/**
	 *  加载布局 
	 * @param activity
	 */
	private static void injectContentView(Activity activity) {
		Class<? extends Activity> clazz = activity.getClass();
		
		ContentView contentView = clazz.getAnnotation(ContentView.class);
		
		if (contentView == null) {
			return;
		}
		// 获取 注解 传递的 值
		int contentViewLayoutId = contentView.value();
		
		try {
			Method method = clazz.getMethod(SET_CONTENTVIEW, int.class);
			method.setAccessible(true);
			method.invoke(activity, contentViewLayoutId);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} 
	}

	/**
	 *  加载 控件view
	 * @param activity
	 */
	private static void injectViews(Activity activity) {
		Class<? extends Activity> clazz = activity.getClass();
		
		Field[] fields = clazz.getDeclaredFields();
		
		// 遍历所有成员变量
		for (Field field : fields) {
			InjectView injectViewAnnotation = field.getAnnotation(InjectView.class);
			
			if (injectViewAnnotation == null) {
				continue;
			}
			int viewId = injectViewAnnotation.value();
			
			if (viewId == -1) {
				continue;
			}
			try {
				Method method = clazz.getMethod(FIND_VIEW_BY_ID,
						int.class);
				Object resView = method.invoke(activity, viewId);
				field.setAccessible(true);
				field.set(activity, resView);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
